import { getCartList, changeCount, delSelect } from '@/api/cart'

export default {
  namespaced: true,
  state () {
    return {
      cartList: [],
      cartTotal: 0
    }
  },
  mutations: {
    setCartList (state, newList) {
      state.cartList = newList
    },
    setCartTotal (state, newCartTotal) {
      state.cartTotal = newCartTotal
    },
    changeCheck (state, goodsId) {
      const goods = state.cartList.find(item => item.goodsId === goodsId)
      goods.isChecked = !goods.isChecked
    },
    changeCheckAll (state, falg) {
      state.cartList.forEach(item => {
        item.isChecked = !falg
      })
    }
  },
  actions: {
    async updateCartList (context) {
      const res = await getCartList()
      res.data.cartList.forEach(item => {
        item.isChecked = true
      })
      context.commit('setCartList', res.data.cartList)
      context.commit('setCartTotal', res.data.total)
    },
    async ChangeCartCountAction (context, obj) {
      const { id, goodsNum } = obj
      await changeCount(id, goodsNum)
      await context.dispatch('updateCartList')
    },
    async delCartAction (context) {
      await delSelect(context.getters.selCartList)
      await context.dispatch('updateCartList')
    }
  },
  getters: {
    selCartList (state) {
      return state.cartList.filter(item => item.isChecked)
    },
    selPrice (state, getters) {
      return getters.selCartList.reduce((sum, item, index) => {
        return sum + item.goodsNum * item.goodsPrice
      }, 0).toFixed(2)
    },
    selCount (state, getters) {
      return getters.selCartList.reduce((sum, item, index) => {
        return sum + item.goodsNum
      }, 0)
    },
    isAllCheckd (state, getters) {
      return getters.selCount === state.cartTotal
    }
  }
}
